/**
 * @file demo_bemfaclient_usage.cpp
 * @brief 巴法云TCP客户端使用演示
 *
 * 演示如何使用BemfaClient类实现远程数据推送功能
 */

#include <QCoreApplication>
#include <QDebug>
#include "../src/io/bemfaclient.h"
#include "../src/core/devicemanager.h"
#include "../src/core/alarmengine.h"
#include "../src/io/serialportmanager.h"
#include "../src/database/dbmanager.h"
#include "../src/utils/config.h"
#include "../src/utils/logger.h"

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    // ========== 1. 初始化日志系统 ==========
    // 使用绝对路径，因为可执行文件在 build/bin/ 目录下
    QString logPath = "C:/Users/86188/Desktop/ModbusPro/QModbusPowerCloud/logs/demo_bemfaclient.log";
    Logger::instance()->initialize(logPath);
    Logger::instance()->info("Demo", "========== 巴法云客户端演示程序启动 ==========");

    // ========== 2. 加载配置文件 ==========
    // 使用绝对路径
    QString configPath = "C:/Users/86188/Desktop/ModbusPro/QModbusPowerCloud/config/settings.ini";
    Config *config = Config::instance();
    if (!config->initialize(configPath))
    {
        qCritical() << "配置文件加载失败！";
        qCritical() << "配置文件路径：" << configPath;
        return -1;
    }

    // 检查是否启用巴法云
    if (!config->isBemfaEnabled())
    {
        qWarning() << "巴法云推送未启用，请在配置文件中设置Bemfa/Enabled=true";
        qWarning() << "配置文件路径：" << configPath;
        qWarning() << "提示：如果需要测试，请确保在巴法云控制台创建了3个主题：";
        qWarning() << "  - powercloud001 (配电室A)";
        qWarning() << "  - powercloud002 (配电室B)";
        qWarning() << "  - powercloud003 (配电室C)";
        return 0;
    }

    // ========== 3. 初始化数据库 ==========
    DBManager *dbManager = DBManager::instance();
    if (!dbManager->initialize(config->getDatabasePath()))
    {
        qCritical() << "数据库初始化失败！";
        return -1;
    }

    // ========== 4. 初始化串口和设备管理器 ==========
    SerialPortManager *portManager = new SerialPortManager();
    DeviceManager *deviceManager = new DeviceManager(portManager);

    // 配置3个配电室（对应3条总线）
    DeviceManager::BusConfig busA{1, "配电室A", config->getSerialPort1(), 1, 40};
    DeviceManager::BusConfig busB{2, "配电室B", config->getSerialPort2(), 41, 80};
    DeviceManager::BusConfig busC{3, "配电室C", config->getSerialPort3(), 81, 120};

    deviceManager->addBusConfig(busA);
    deviceManager->addBusConfig(busB);
    deviceManager->addBusConfig(busC);

    // ========== 5. 初始化报警引擎 ==========
    AlarmEngine *alarmEngine = new AlarmEngine(dbManager);
    alarmEngine->start();

    // ========== 6. 创建巴法云客户端 ==========
    BemfaClient *bemfaClient = new BemfaClient();

    // 初始化客户端
    QString host = config->getBemfaHost();
    int port = config->getBemfaPort();
    QString uid = config->getBemfaUid();

    if (!bemfaClient->initialize(host, port, uid))
    {
        qCritical() << "巴法云客户端初始化失败！";
        return -1;
    }

    qInfo() << "巴法云客户端初始化成功";
    qInfo() << "服务器：" << host << ":" << port;
    qInfo() << "用户UID：" << uid;

    // ========== 7. 配置配电室主题 ==========
    BemfaClient::RoomInfo roomA{
        1,                        // roomId
        "配电室A",                // roomName
        config->getBemfaTopic1(), // topic: powercloud001
        1,                        // startMeterId
        40                        // endMeterId
    };

    BemfaClient::RoomInfo roomB{
        2,
        "配电室B",
        config->getBemfaTopic2(), // topic: powercloud002
        41,
        80};

    BemfaClient::RoomInfo roomC{
        3,
        "配电室C",
        config->getBemfaTopic3(), // topic: powercloud003
        81,
        120};

    bemfaClient->addRoomConfig(roomA);
    bemfaClient->addRoomConfig(roomB);
    bemfaClient->addRoomConfig(roomC);

    qInfo() << "配电室主题配置完成：";
    qInfo() << "  配电室A -> " << config->getBemfaTopic1() << " (站号1-40)";
    qInfo() << "  配电室B -> " << config->getBemfaTopic2() << " (站号41-80)";
    qInfo() << "  配电室C -> " << config->getBemfaTopic3() << " (站号81-120)";

    // ========== 8. 关联设备管理器和报警引擎 ==========
    bemfaClient->setDeviceManager(deviceManager);
    bemfaClient->setAlarmEngine(alarmEngine);

    // ========== 9. 连接信号槽 ==========
    QObject::connect(bemfaClient, &BemfaClient::connectionEstablished, []()
                     { qInfo() << "✓ 成功连接到巴法云服务器！"; });

    QObject::connect(bemfaClient, &BemfaClient::connectionLost, []()
                     { qWarning() << "✗ 与巴法云服务器断开连接！"; });

    QObject::connect(bemfaClient, &BemfaClient::subscribeSucceeded, [](const QString &topics)
                     { qInfo() << "✓ 订阅成功：" << topics; });

    QObject::connect(bemfaClient, &BemfaClient::messageReceived,
                     [bemfaClient](const QString &topic, const QString &message)
                     {
                         qInfo() << "收到消息 [" << topic << "]：" << message;

                         // 处理APP查询请求
                         if (message.startsWith("query:"))
                         {
                             int meterId = message.mid(6).toInt();
                             qInfo() << "收到查询请求，电表ID：" << meterId;
                             // 这里可以实现返回指定电表的详细数据
                             // bemfaClient->publishMeterDetail(meterId);
                         }
                     });

    QObject::connect(bemfaClient, &BemfaClient::errorOccurred, [](const QString &error)
                     { qWarning() << "✗ 错误：" << error; });

    // ========== 10. 连接到巴法云服务器 ==========
    qInfo() << "正在连接到巴法云服务器...";
    bemfaClient->connectToServer();

    // ========== 11. 启动自动推送 ==========
    int dataPushInterval = config->getBemfaDataPushInterval();
    int fullDataUploadInterval = config->getBemfaFullDataUploadInterval();

    bemfaClient->startAutoPush(dataPushInterval, fullDataUploadInterval);

    qInfo() << "自动推送已启动：";
    qInfo() << "  汇总数据推送间隔：" << dataPushInterval << "秒";
    qInfo() << "  全量数据上传间隔：" << fullDataUploadInterval << "秒";
    qInfo() << "  报警事件：即时推送";

    // ========== 12. 演示：测试简单消息 ==========
    QTimer::singleShot(3000, [bemfaClient]()
                       {
                           qInfo() << "\n========== 测试：发送简单文本消息 ==========";
                           bool success1 = bemfaClient->publish("powercloud001", "test");
                           qInfo() << "发送 'test' 到 powercloud001：" << (success1 ? "成功" : "失败");
                           
                           bool success2 = bemfaClient->publish("powercloud001", "on");
                           qInfo() << "发送 'on' 到 powercloud001：" << (success2 ? "成功" : "失败"); });

    // ========== 13. 演示：手动推送汇总数据 ==========
    // 注意：实际使用时，数据会自动从DeviceManager获取
    // 这里仅为演示如何手动调用推送接口

    QTimer::singleShot(5000, [bemfaClient]()
                       {
                           qInfo() << "\n========== 演示：手动推送汇总数据 ==========";
                           bemfaClient->pushRoomSummary(0); // 0表示推送所有配电室
                       });

    QTimer::singleShot(8000, [bemfaClient]()
                       {
                           qInfo() << "\n========== 演示：手动上传全量数据 ==========";
                           bemfaClient->uploadFullData(0); // 0表示上传所有配电室
                       });

    // ========== 14. 说明：为什么推送失败 ==========
    qInfo() << "\n注意：演示程序中 DeviceManager 没有实际电表数据";
    qInfo() << "因此推送的JSON只包含统计信息（online=0, offline=0）";
    qInfo() << "在生产环境中，需要先执行设备拓扑识别或从数据库加载电表数据";
    qInfo() << "然后 DeviceManager 才会有电表对象，推送才会包含真实数据\n";

    // ========== 15. 演示：模拟报警事件 ==========
    QTimer::singleShot(15000, [alarmEngine, deviceManager, dbManager]()
                       {
        qInfo() << "\n========== 演示：模拟报警事件 ==========";
        
        // 创建一个测试电表（先保存到数据库）
        // 注意：站号25在1-40范围内，属于配电室A
        int testMeterId = 25;
        MeterInfo meterInfo;
        meterInfo.meterId = testMeterId;
        meterInfo.name = "测试电表-25";
        meterInfo.location = "配电室A";  // 站号25属于配电室A
        meterInfo.busId = 1;              // busId=1 对应配电室A
        meterInfo.enabled = true;
        meterInfo.createTime = QDateTime::currentDateTime();
        meterInfo.updateTime = QDateTime::currentDateTime();
        dbManager->saveMeterInfo(meterInfo);
        
        Meter *testMeter = new Meter(testMeterId, "测试电表-25", "配电室A", 1);
        testMeter->setOnline(true);
        testMeter->setUa(180.0);  // 电压跌落！
        testMeter->setIa(15.0);
        
        // 添加到报警引擎监控
        alarmEngine->addMeter(testMeter);
        
        // 触发报警检测
        alarmEngine->checkMeter(testMeter);
        
        qInfo() << "已触发电压跌落报警（25号表，Ua=180V < 200V）";
        qInfo() << "报警将自动推送到 powercloud001 主题（配电室A，站号1-40）"; });

    // ========== 16. 演示数据统计 ==========
    QTimer *statsTimer = new QTimer();
    QObject::connect(statsTimer, &QTimer::timeout, [bemfaClient]()
                     {
        qInfo() << "\n========== 数据统计 ==========";
        qInfo() << "连接状态：" << (bemfaClient->isConnected() ? "已连接" : "未连接");
        qInfo() << "状态描述：" << bemfaClient->status();
        qInfo() << "已发送：" << bemfaClient->bytesSent() << " 字节";
        qInfo() << "已接收：" << bemfaClient->bytesReceived() << " 字节"; });
    statsTimer->start(30000); // 每30秒输出一次统计

    // ========== 17. 运行程序 ==========
    qInfo() << "\n程序运行中，按Ctrl+C退出...";
    qInfo() << "========================================\n";

    int ret = app.exec();

    // ========== 18. 清理资源 ==========
    bemfaClient->stopAutoPush();
    bemfaClient->disconnectFromServer();

    delete statsTimer;
    delete bemfaClient;
    delete alarmEngine;
    delete deviceManager;
    delete portManager;

    Logger::instance()->info("Demo", "程序退出");
    return ret;
}
